package com.westcom.secritycheck.WaitingLine.impl;

import com.westcom.secritycheck.bean.Passenger;
import com.westcom.secritycheck.WaitingLine.IWaitingLine;
import com.westcom.secritycheck.constants.Constants;
import com.westcom.secritycheck.constants.Utils;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;

/*
 * auth:zoupeng
 * date:20180904
 * */
public class LinkedListWaitingLine implements IWaitingLine
{
    LinkedList<Passenger> line = new LinkedList<>();
    Object lock = new Object();
    public int push(Passenger p)
    {
        synchronized(lock)
        {
            int index = calculateIndex(p);
            p.setInLineTimestamp(System.currentTimeMillis());
            line.add(index,p);
            Utils.printLog(p.toString(),"added");
            return index;
        }
    }
    private int calculateIndex(Passenger p)
    {
        if(Constants.PassengerType.pregnancy == p.getType() || Constants.PassengerType.handicapped == p.getType() || 0 == line.size())
        {
            return 0;
        }
        if(p.getAge()<60)
        {
            return line.size();
        }
        for(int i = line.size()-1;i>=0;i--)
        {
            if(line.get(i).getAge()>p.getAge())
            {
                return i;
            }
        }
        return 0;
    }
    public Passenger offer()
    {
        return line.pollFirst();
    }
    @Override
    public void print()
    {
        StringBuffer sb = new StringBuffer();
        sb.append("left:").append(System.lineSeparator());
        for(Passenger p:line)
        {
            sb.append(p.toString()).append(System.lineSeparator());
        }
        Utils.printLog(sb.toString());
    }

    @Override
    public long size() {
        return line.size();
    }
}
